#include <REG167.H>
#include "RingBuf.h"
#include "uart.h"

sbit DP3_10 = DP3^10;    
sbit P3_10 = P3^10;    
sbit DP3_11 = DP3^11;    
sbit P3_11 = P3^11;    

static void UartTransmit(char data);

// don't acccess this memory directly
unsigned char __TXBuf[TXBUF_LEN];
unsigned char __RXBuf[RXBUF_LEN];

// use these structs instead
struct RingBuf TxRingBuf, RxRingBuf;
int UartBusy;


void UartInit(void)
{
	S0CON = 0x8011;
	S0BG = 0x40;
	
	DP3_10 = 1;
	P3_10 = 1;
	DP3_11 = 0;
	P3_11 = 1;	

	S0RIC = 0x48;
	S0TIC = 0x44;
	InitBuffer(&TxRingBuf, TXBUF_LEN, __TXBuf);
	InitBuffer(&RxRingBuf, RXBUF_LEN, __RXBuf);
}
void UartReceiveISR(void) interrupt 0x2B
{
	// store every received byte
	AddByte(&TxRingBuf, S0RBUF);
	
	if ((S0RBUF == ' ') && (!UartBusy))
	{
		// received an "end of message" char, send response
		UartTransmit(GetByte(&TxRingBuf));
		UartBusy = 1;
	}
}
void UartTransmit(char data)
{
	S0TBUF = data;
}

void UartTransmitISR(void) interrupt 0x2A
{
	if (TxRingBuf.Content)
		UartTransmit(GetByte(&TxRingBuf));
	else
		UartBusy = 0;
}


